package top.kaoshanji.p1ch07a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch07a-227页a：设置超时值，单位是秒
 * URL访问地址：/sessionTimer
 * @author kaoshanji
 * ^_^
 * create time 2025/4/4 19:43
 */
public class SessionTimer extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        // 取得当前会话对象，必要时生成一个
        HttpSession session = req.getSession();

        out.println("<HTML><HEAD><TITLE>SessionTimer</TITLE></HEAD>");
        out.println("<BODY><H1>Session Timer</H1>");

        // 显示原来的超时
        out.println("The previous timeout was " + session.getMaxInactiveInterval());
        out.println("<BR>");

        // 设置新的超时
        session.setMaxInactiveInterval(2 * 60 * 60); // 2小时

        // 显示新的超时
        out.println("The newly assigned timeout is " + session.getMaxInactiveInterval());

        out.println("</BODY></HTML>");
    }

}
